package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func main() {

	r := gin.Default()
	r.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		action = strings.Trim(action, "/")
		c.String(http.StatusOK, name+" is "+action)
	})

	r.GET("/user", func(c *gin.Context) {
		name := c.DefaultQuery("name", "张三")
		c.String(http.StatusOK, fmt.Sprintf("你好，%s", name))
	})
	r.POST("/form", func(c *gin.Context) {
		types := c.DefaultPostForm("type", "post")
		username := c.PostForm("username")
		password := c.PostForm("password")
		c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types))
	})
	//上传文件学习
	r.POST("/upload", func(c *gin.Context) {
		//r.Static("/uploads", "./uploads")
		file, err := c.FormFile("file")
		if err != nil {
			c.JSON(400, gin.H{
				"message": "文件上传失败",
			})
			return
		}
		if file.Size > 10*1024*1024 {
			c.JSON(400, gin.H{
				"message": "文件太大",
			})
			return
		}
		err = c.SaveUploadedFile(file, "uploads/"+file.Filename)
		if err != nil {
			c.JSON(500, gin.H{
				"message": "文件保存失败",
			})
			return
		}
		c.JSON(200, fmt.Sprintf("文件%s上传成功", file.Filename))
	})
	r.Run(":8080")
}
